
package com.management.department.teacherinfosystem.config;

import com.management.department.teacherinfosystem.Entity.Role;
import com.management.department.teacherinfosystem.Entity.TeachingProject;
import com.management.department.teacherinfosystem.Entity.TeachingProjectMember;
import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Entity.ProjectFunding;
import com.management.department.teacherinfosystem.Entity.AcademicAchievement;
import com.management.department.teacherinfosystem.Entity.AcademicAchievementAuthor;
import com.management.department.teacherinfosystem.Entity.AcademicAchievementAttachment;
import com.management.department.teacherinfosystem.Repository.RoleRepository;
import com.management.department.teacherinfosystem.Repository.TeachingProjectMemberRepository;
import com.management.department.teacherinfosystem.Repository.TeachingProjectRepository;
import com.management.department.teacherinfosystem.Repository.UserRepository;
import com.management.department.teacherinfosystem.Repository.ProjectFundingRepository;
import com.management.department.teacherinfosystem.Repository.AcademicAchievementRepository;
import com.management.department.teacherinfosystem.Repository.AcademicAchievementAuthorRepository;
import com.management.department.teacherinfosystem.Repository.AcademicAchievementAttachmentRepository;
import com.management.department.teacherinfosystem.Service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

// @Component  // 已禁用数据初始化，防止重复创建测试数据
@RequiredArgsConstructor
@Transactional
public class DataInitializer implements ApplicationRunner {

    private final RoleRepository roleRepository;
    private final UserService userService;
    private final UserRepository userRepository;
    private final TeachingProjectRepository projectRepository;
    private final TeachingProjectMemberRepository memberRepository;
    private final ProjectFundingRepository fundingRepository;
    private final AcademicAchievementRepository academicAchievementRepository;
    private final AcademicAchievementAuthorRepository academicAuthorRepository;
    private final AcademicAchievementAttachmentRepository academicAttachmentRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 1) 角色
        createRoleIfAbsent("admin", "系统管理员");
        createRoleIfAbsent("manager", "管理员/秘书");
        createRoleIfAbsent("teacher", "教职工");

        // 2) 用户
        ensureUser("admin", "admin123", "系统管理员", "管理系", "admin");
        User t1 = ensureUser("t001", "123456", "张三", "信息管理系", "teacher");
        User t2 = ensureUser("t002", "123456", "李四", "信息管理系", "teacher");

        // 3) 示例项目（总是重新创建测试数据以确保符合新流程）
        fundingRepository.deleteAll(); // 清空现有经费数据
        memberRepository.deleteAll();  // 清空现有成员数据
        projectRepository.deleteAll(); // 清空现有项目数据
        
        // 创建不同状态的测试项目
        createTestProject(t1, "智慧教学平台建设", "课程建设项目", "省部级", "申报中", 50000);
        createTestProject(t2, "教学方法创新研究", "教改项目", "校级", "申报中", 20000);
        createTestProject(t1, "Python程序设计教材编写", "教材建设项目", "国家级", "已立项", 100000);
        createTestProject(t2, "实验教学改革实践", "实践教学项目", "省部级", "执行中", 30000);
        createTestProject(t1, "数据结构课程改革", "课程建设项目", "校级", "结题审核中", 15000);
        createTestProject(t2, "信息系统分析与设计", "课程建设项目", "市厅级", "已结题", 25000);
        
        // 4) 学术成果测试用例
        createTestAcademicAchievement(t1, "基于深度学习的教学模式创新研究", "期刊论文", "中文", "深度学习,教学模式,创新", "教育研究", 2024, 3, "10.1234/edu.2024.001", "CSSCI核心", null, "PENDING");
        createTestAcademicAchievement(t2, "大数据时代下的信息管理教育变革", "会议论文", "中文", "大数据,信息管理,教育变革", "全国信息管理教育年会", 2024, 6, null, null, "国内重要", "APPROVED");
        createTestAcademicAchievement(t1, "人工智能在高等教育中的应用前景", "期刊论文", "英文", "人工智能,高等教育,应用前景", "International Journal of Education", 2023, 12, "10.5678/ijed.2023.005", "SSCI一区", null, "REJECTED");
    }

    private void createRoleIfAbsent(String name, String desc) {
        roleRepository.findByName(name).orElseGet(() -> {
            Role r = new Role();
            r.setName(name);
            r.setDescription(desc);
            return roleRepository.save(r);
        });
    }

    private User ensureUser(String username, String password, String name,
                            String department, String roleCode) {
        return userRepository.findByUsername(username).orElseGet(() ->
                userService.createUser(username, password, name, department, roleCode)
        );
    }

    private void createTestProject(User leader, String name, String type, String level, String status, double funding) {
        TeachingProject p = new TeachingProject();
        p.setName(name);
        p.setProjectNumber("PRJ" + System.currentTimeMillis() % 100000); // 简单的项目编号
        p.setProjectType(type);
        p.setLevel(level);
        p.setLeaderId(leader.getId());
        p.setStatus(status);
        
        Date now = new Date();
        p.setApplicationDate(now);
        p.setStartDate(now);
        p.setCreatedAt(now);
        p.setUpdatedAt(now);
        
        // 根据状态设置不同的日期和信息
        if ("已立项".equals(status) || "执行中".equals(status) || "结题审核中".equals(status) || "已结题".equals(status)) {
            p.setApprovalDate(now);
            p.setApprovalDepartment("教务处");
        }
        
        if ("结题审核中".equals(status) || "已结题".equals(status)) {
            p.setFinishDate(now);
            p.setFinishType("验收");
            p.setFinishLevel("良好");
            p.setFinishResults("完成教学改革实践，发表论文2篇，编写教材1部");
        }
        
        TeachingProject saved = projectRepository.save(p);

        // 创建项目经费信息
        ProjectFunding f1 = new ProjectFunding(saved.getId(), new BigDecimal(funding * 0.6), "设备购置");
        ProjectFunding f2 = new ProjectFunding(saved.getId(), new BigDecimal(funding * 0.3), "差旅费");
        ProjectFunding f3 = new ProjectFunding(saved.getId(), new BigDecimal(funding * 0.1), "材料费");
        fundingRepository.save(f1);
        fundingRepository.save(f2);
        fundingRepository.save(f3);

        // 创建项目成员
        TeachingProjectMember m1 = new TeachingProjectMember();
        m1.setProjectId(saved.getId());
        m1.setUserId(leader.getId());
        m1.setRole("负责人");
        m1.setDepartment(leader.getDepartment());
        m1.setCreatedAt(now);
        memberRepository.save(m1);
    }
    
    private void createTestAcademicAchievement(User author, String title, String type, String language, 
                                             String keywords, String journalConference, int year, int month,
                                             String doi, String journalLevel, String conferenceLevel, String status) {
        AcademicAchievement achievement = new AcademicAchievement();
        achievement.setTitle(title);
        achievement.setType(type);
        achievement.setLanguage(language);
        achievement.setKeywords(keywords);
        achievement.setJournalConference(journalConference);
        achievement.setPublicationYear(year);
        achievement.setPublicationMonth(month);
        achievement.setDoi(doi);
        achievement.setJournalLevel(journalLevel);
        achievement.setConferenceLevel(conferenceLevel);
        achievement.setStatus(status);
        achievement.setCreatedBy(author.getId());
        
        Date now = new Date();
        achievement.setCreatedAt(now);
        achievement.setUpdatedAt(now);
        
        if ("APPROVED".equals(status) || "REJECTED".equals(status)) {
            achievement.setReviewOpinion("测试审核意见");
            achievement.setReviewerId(1L); // admin用户ID
            achievement.setReviewTime(now);
        }
        
        AcademicAchievement saved = academicAchievementRepository.save(achievement);
        
        // 创建作者信息
        AcademicAchievementAuthor authorInfo = new AcademicAchievementAuthor();
        authorInfo.setAchievementId(saved.getId());
        authorInfo.setAuthorName(author.getName());
        authorInfo.setAuthorUnit(author.getDepartment());
        authorInfo.setAuthorOrder("第一作者");
        authorInfo.setIsCurrentUnit(true);
        authorInfo.setStaffNo(author.getStaffNo());
        authorInfo.setCreatedAt(now);
        academicAuthorRepository.save(authorInfo);
        
        // 创建附件信息（模拟）
        AcademicAchievementAttachment attachment = new AcademicAchievementAttachment();
        attachment.setAchievementId(saved.getId());
        attachment.setFileName("测试附件.pdf");
        attachment.setFileUrl("uploads/academic_achievements/test_attachment.pdf");
        attachment.setFileType("PDF");
        attachment.setFileSize(1024000L); // 1MB
        attachment.setCreatedAt(now);
        academicAttachmentRepository.save(attachment);
    }
}


